import { store } from '@/store'
import { defineStore } from 'pinia'
import * as CartApi from '@/api/shop/trade/cart'
import { cloneDeep } from 'lodash-es'

// const { push } = useRouter() // 路由跳转
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()

/** 密码键盘信息 */
import { useShopKeyboardWithOut } from './keyBoard'
const shopKeyboard = useShopKeyboardWithOut()

declare interface ShopServiceVO {
  orderId: string | undefined //订单号
  totalPerformanceFee: number //消耗业绩
  replaceItems: EmptyArrayType //更换项目列表
  itemsNum: number //卡项数量
  itemsTimes: number //使用次数
  itemsList: EmptyArrayType //购物车列表
  orderPayload: any
}

export const useShopService = defineStore('shop-service', {
  state: (): ShopServiceVO => ({
    orderId: undefined, //订单号
    totalPerformanceFee: 0, //消耗业绩
    itemsTimes: 0, //使用次数
    itemsList: [],
    replaceItems: [], //更换项目列表
    itemsNum: 0, //卡项数量.
    orderPayload: {} //订单支付加载信息
  }),
  getters: {
    getCartNumber(): number {
      return this.itemsList.length
    }, //购物车服务列表数量
    getCartList(): EmptyArrayType {
      return this.itemsList
    }, //购物车服务列表
    getOrderPayload(): any {
      return this.orderPayload
    }, //获取订单支付信息
    getReplaceItems(): EmptyArrayType {
      return this.replaceItems
    }, //购物车要换卡项的列表
    getServiceReplaceList(): EmptyArrayType {
      const checklist = this.itemsList.filter((ele) => {
        return ele.replaced
      })
      return checklist
    }, //服务被换卡列表 订单信息展示
    getTotalPerformanceFee(): number {
      return this.totalPerformanceFee
    },
    getServiceInfo(): EmptyArrayType {
      const servicelist = this.itemsList.filter((ele) => {
        return !ele.replaced
      })
      const replaceItems = this.replaceItems
      // 下方操作为了统一不一样的数据解构
      const processServicelist = servicelist.map((ele) => {
        return {
          spuName: ele.spu.spuName,
          skuSerialName: ele.sku.skuSerialName,
          usedTimes: ele.count
        }
      })
      const processReplaceItems = replaceItems.map((ele) => {
        return {
          spuName: ele.spu.spuName,
          skuSerialName: ele.sku.skuSerialName,
          usedTimes: ele.count
        }
      })
      const list = processServicelist.concat(processReplaceItems)

      return list
    }, //服务详情里展示的服务信息 自己筛选 没有换卡的就是服务信息。

    getOrderId(): any {
      return this.orderId
    }
  },
  actions: {
    // 获取购物车列表
    async getList() {
      const cartParams = {
        userId: shopUserStore.getUser.id
      }
      try {
        const data = await CartApi.getServiceCartList(cartParams)
        this.itemsList = data.validList
        this.orderId = data.no
        this.setOrderPayload()
        const list = this.getServiceReplaceList
        // console.log(list)
        if (list.length > 0) {
          await this.getReplaceList()
        }
        return data
      } finally {
      }
    },
    async getReplaceList() {
      const cartParams = {
        userId: shopUserStore.getUser.id
      }
      try {
        const data = await CartApi.getServiceCartListH(cartParams)
        this.replaceItems = data.validList

        this.setOrderPayload()

        return data
      } finally {
      }
    },
    /** 设置 订单支付信息 */
    setOrderPayload() {
      const list = this.itemsList
      const replaceList = this.replaceItems
      const items = [] as EmptyArrayType
      list.concat(replaceList).map((item) => {
        items.push({
          skuId: item.sku.skuId,
          count: item.count,
          cartId: item.id,
          categoryId: item.spu.categoryId
        })
      })
      this.orderPayload = {
        items: items
      }
    },

    /** 服务 购物车 */
    async addCart(cartItem: CartApi.serviceCartItemVO) {
      try {
        const cartParams = {
          walletId: cartItem.id,
          userId: shopUserStore.getUser.id,
          count: cartItem.goods_num ? cartItem.goods_num : 1
        }

        await CartApi.addServiceCart(cartParams)
      } finally {
        await this.getList()
      }
    },
    /** 服务 更新购物车 */
    async updateCart(cartParams: any) {
      try {
        cartParams.userId = shopUserStore.getUser.id
        await CartApi.updateCartCount(cartParams)
      } finally {
        await this.getList()
      }
    },
    async deleteCart(item: CartApi.serviceCartItemVO) {
      try {
        const deepCartItem = cloneDeep(item) //因为协议 使用的传参和可用资产的的结果基本相同 故深拷贝当前使用的优惠券

        const cartParams = {
          userId: shopUserStore.getUser.id,
          ids: deepCartItem.id
        }

        await CartApi.deleteCart(cartParams)
      } finally {
        await this.getList()
      }
    },

    async addReplaceCart(cartItem: CartApi.cartItemVO) {
      try {
        const cartParams = {
          skuId: cartItem.skuId,
          count: cartItem.goods_num,
          userId: shopUserStore.getUser.id
        }

        await CartApi.addReplaceCart(cartParams)
      } finally {
        await this.getList()
      }
    },

    restSalesStateData() {
      this.$reset()
    }, //清除销售信息

    handleOpenCodeKeyboard() {
      const codeKeyboardConfig = {
        dialogVisible: true,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(codeKeyboardConfig)
    }, //打开密码框
    closeCodeKeyBoard() {
      const config = {
        dialogVisible: false,
        title: '请输入密码', //数字键盘弹框的标题
        keyboardValue: ''
      }
      shopKeyboard.setCodeKeyboardConfig(config)
    }
  }
})
export const useShopServiceWithOut = () => {
  return useShopService(store)
}
